import React, {Component} from 'react';
import reactDom from 'react-dom';

import Uploader from '../../../../../public/components/UploaderImgWithBase64';

import {
    toast
} from 'nc-lightapp-front';

import language from '../../../language';
import {getColor} from '../../../../../../hrpub/common/utils/utils';

const imageList = ['.png', '.jpg', '.gif', '.jpeg'];

export default function () {


    const {
        form: {
            setFormItemsVisible
        },
        imageData,
        MultiInit,
        photoConf = {}
    } = this.props;

    const {bgColor} = getColor();

    setFormItemsVisible('bd_psndoc', {
        photo: false
    });

    if (document.getElementById('photoDiv')) {
        let pdiv = document.getElementById('photoDiv')
        // let img = d.getElementsByTagName('img')[0]
        pdiv.parentNode.removeChild(pdiv) // 如果这里只替换src不清除dom， 则由有照片切换到无照片时会出现图片加载失败的图标
    }
    let timer = null;
    const check = () => {
        let oFormBox = document.getElementById('form_bd_psndoc').children[0];
        let obox = oFormBox.querySelectorAll("div[class='group-form-item lightapp-component-form show-form']")[0];
        if (obox) {
            let oDiv = document.createElement('div');
            oDiv.id = 'photoDiv';
            oDiv.style.float = 'right';
            oDiv.style.marginRight = '10px';
            oDiv.style.marginTop = '8px';
            oDiv.style.backgroundColor = bgColor;
            obox.insertBefore(oDiv, obox.children[0]);

            let photoDiv = document.getElementById('photoDiv')
            reactDom.render(<Uploader
                label={photoConf.label}
                ref={(ref) => {
                    this.props.setUpLoaderRef(ref);
                }}
                onUpload={(result, file) => {
                    let filename = file.name;
                    let fileExt = filename.substring(filename.lastIndexOf('.'));

                    if (imageList.includes(fileExt.toLowerCase())) {
                        this.props.updateState({
                            imageData: result
                        })
                    } else {
                        toast({
                            color: 'danger',
                            content: language['hi6007-000177'] /* 上传格式不正确 */
                        });

                        return false;
                    }
                }}
                value={imageData}
                MultiInit={MultiInit}
            />, photoDiv);
            if (timer) {
                clearTimeout(timer)
            }
        } else {
            timer = setTimeout(check, 100)
        }
    }
    check();
}
